package com.atguigu.guli.api.gateway.filter;


import com.atguigu.guli.service.base.result.ResultCodeEnum;
import com.atguigu.guli.service.base.utils.JwtHelper;
import com.google.gson.JsonObject;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

@Component
public class GlobalAuthFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //参数1：交换机 参数2：filter链
        //统一鉴权
        //1.判断当前请求是否需要鉴权（是否携带"/api/**/auth/**"）
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String uri = request.getURI().getPath();
        AntPathMatcher matcher = new AntPathMatcher() ;
        boolean flag = matcher.match("/api/**/auth/**", uri);
        if (!flag) {
            //2.不需要鉴权，放行
            return chain.filter(exchange) ;
        }
        //3.从请求头中取出token
        String token = request.getHeaders().getFirst("token");
        boolean checkToken = JwtHelper.checkToken(token);
        if (checkToken) {
            //4.鉴权通过，放行
            return chain.filter(exchange) ;
        }
        //5.鉴权失败，封装R对象返回
        JsonObject jsonObject = new JsonObject() ;
        jsonObject.addProperty("success", ResultCodeEnum.LOGIN_AUTH.getSuccess());
        jsonObject.addProperty("code", ResultCodeEnum.LOGIN_AUTH.getCode());
        jsonObject.addProperty("message", ResultCodeEnum.LOGIN_AUTH.getMessage());
        String s = jsonObject.toString();
        DataBuffer dataBuffer = response.bufferFactory().wrap(s.getBytes(StandardCharsets.UTF_8));
        response.getHeaders().add("content-type","application/json;charset=UTF-8");
        return response.writeWith(Mono.just(dataBuffer));
    }


    //返回值越小 当前filter执行的优先级越高
    @Override
    public int getOrder() {
        return 0;
    }
}
